<template>
  <div class="admin-medicine">
    <div class="header">
      <h2>药品管理</h2>
      <el-button type="primary" @click="handleAdd">新增药品</el-button>
    </div>

    <!-- 搜索筛选 -->
    <div class="filter">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="药品名称">
          <el-input v-model="searchForm.medicineName" placeholder="请输入药品名称" clearable />
        </el-form-item>
        <el-form-item label="药品类型">
          <el-select v-model="searchForm.medicineType" placeholder="请选择药品类型" clearable>
            <el-option label="处方药" value="prescription" />
            <el-option label="非处方药" value="non-prescription" />
            <el-option label="保健品" value="health" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="有效" value="active" />
            <el-option label="失效" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 药品列表 -->
    <div class="table">
      <el-table :data="medicineList" v-loading="loading" border>
        <el-table-column prop="medicineId" label="药品ID" width="100" align="center" />
        <el-table-column prop="medicineName" label="药品名称" min-width="150" />
        <el-table-column prop="medicineType" label="药品类型" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getMedicineTypeTag(row.medicineType)">
              {{ getMedicineTypeText(row.medicineType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="specification" label="规格" width="120" align="center" />
        <el-table-column prop="unit" label="单位" width="80" align="center" />
        <el-table-column prop="stock" label="库存数量" width="100" align="center" />
        <el-table-column prop="usage" label="用法用量" min-width="200" />
        <el-table-column prop="description" label="药品说明" min-width="200" />
        <el-table-column prop="expiryDate" label="有效期" width="120" align="center">
          <template #default="{ row }">
            {{ formatDate(row.expiryDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '有效' : '失效' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="warning" size="small" @click="handleStatus(row)">
              {{ row.status === 'active' ? '设为失效' : '设为有效' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="药品名称" prop="medicineName">
          <el-input v-model="form.medicineName" placeholder="请输入药品名称" />
        </el-form-item>
        <el-form-item label="药品类型" prop="medicineType">
          <el-select v-model="form.medicineType" placeholder="请选择药品类型">
            <el-option label="处方药" value="prescription" />
            <el-option label="非处方药" value="non-prescription" />
            <el-option label="保健品" value="health" />
          </el-select>
        </el-form-item>
        <el-form-item label="规格" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入药品规格" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input-number v-model="form.stock" :min="0" :precision="0" />
        </el-form-item>
        <el-form-item label="用法用量" prop="usage">
          <el-input
            v-model="form.usage"
            type="textarea"
            :rows="3"
            placeholder="请输入用法用量说明"
          />
        </el-form-item>
        <el-form-item label="药品说明" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入药品说明"
          />
        </el-form-item>
        <el-form-item label="有效期" prop="expiryDate">
          <el-date-picker
            v-model="form.expiryDate"
            type="date"
            placeholder="请选择有效期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMedicines, addMedicine, updateMedicine, updateMedicineStatus } from '@/api/medicine'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref()
const medicineList = ref([])

// 搜索表单
const searchForm = reactive({
  medicineName: '',
  medicineType: '',
  status: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单数据
const form = reactive({
  medicineId: '',
  medicineName: '',
  medicineType: '',
  specification: '',
  unit: '',
  stock: 0,
  usage: '',
  description: '',
  expiryDate: ''
})

// 表单验证规则
const rules = {
  medicineName: [{ required: true, message: '请输入药品名称', trigger: 'blur' }],
  medicineType: [{ required: true, message: '请选择药品类型', trigger: 'change' }],
  specification: [{ required: true, message: '请输入药品规格', trigger: 'blur' }],
  unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存数量', trigger: 'blur' }],
  usage: [{ required: true, message: '请输入用法用量', trigger: 'blur' }]
}

// 计算属性
const dialogTitle = ref('新增药品')

// 方法
const getMedicineTypeText = (type) => {
  const typeMap = {
    'prescription': '处方药',
    'non-prescription': '非处方药',
    'health': '保健品'
  }
  return typeMap[type] || type
}

const getMedicineTypeTag = (type) => {
  const tagMap = {
    'prescription': 'danger',
    'non-prescription': 'warning',
    'health': 'success'
  }
  return tagMap[type] || ''
}

const formatDate = (date) => {
  if (!date) return ''
  return date.split('T')[0]
}

// 加载药品列表
const loadMedicines = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: pagination.current,
      size: pagination.size
    }
    const response = await getMedicines(params)
    medicineList.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('加载药品列表失败:', error)
    ElMessage.error('加载药品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadMedicines()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.current = 1
  loadMedicines()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadMedicines()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  loadMedicines()
}

// 新增药品
const handleAdd = () => {
  dialogTitle.value = '新增药品'
  Object.keys(form).forEach(key => {
    form[key] = ''
  })
  form.stock = 0
  dialogVisible.value = true
}

// 编辑药品
const handleEdit = (row) => {
  dialogTitle.value = '编辑药品'
  Object.keys(form).forEach(key => {
    form[key] = row[key] || ''
  })
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (form.medicineId) {
      // 编辑
      await updateMedicine(form)
      ElMessage.success('编辑药品成功')
    } else {
      // 新增
      await addMedicine(form)
      ElMessage.success('新增药品成功')
    }
    
    dialogVisible.value = false
    loadMedicines()
  } catch (error) {
    console.error('提交失败:', error)
    if (error.errors) {
      ElMessage.error('请完善表单信息')
    } else {
      ElMessage.error('操作失败')
    }
  } finally {
    submitting.value = false
  }
}

// 状态切换
const handleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 'active' ? '设为失效' : '设为有效'}该药品吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const newStatus = row.status === 'active' ? 'inactive' : 'active'
    await updateMedicineStatus(row.medicineId, newStatus)
    ElMessage.success('操作成功')
    loadMedicines()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 生命周期
onMounted(() => {
  loadMedicines()
})
</script>

<style scoped>
.admin-medicine {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.table {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
}
</style>
